<route lang="json5" type="page">
// @formatter:off
{
  layout: 'theme',
  style: {
    navigationBarTitleText: '请求测试页面',
    // navigationStyle: 'default', // custom default
  }
}
 // @formatter:on
</route>

<script setup lang="ts">
import { awaitToJsTestApi, getLongRequestApi, getTestApi, getTestWithKeyApi, postTestApi } from '@/api'

const pageData = ref()

async function getTestWithKey() {
  try {
    const res = await getTestWithKeyApi({ name: 'uni-fteam' })
    pageData.value = res
    console.log('res.data', res.fteam)
    console.log('res.data.userName', res.fteam.userName)
    console.log('res.msg', res.msg)
    console.log('res.success', res.success)
  } catch (e) {
    console.log(e)
  }
}

async function getTest() {
  const res = await getTestApi({ name: 'uni-fteam' })
  pageData.value = res
}

// POST 请求
const postTest = async () => {
  pageData.value = await postTestApi({ name: 'uni-fteam' }, { id: '123456' })
}

// 长时间请求（测试取消请求）
let requestTask = null
const delayRequest = () => {
  requestTask = getLongRequestApi({ name: 'uni-fteam' })
  requestTask
    .then((res) => {
      pageData.value = res
    })
    .catch((err) => {
      pageData.value = err
    })
}

// 取消 请求
const cancelRequest = () => {
  // 取消请求
  requestTask.abort()
  pageData.value = { msg: '取消请求' }
}

/* await-to-js 代替 try catch 用法，根据实际需求进行使用 */
const awaitToJs = async () => {
  const [data, err] = await awaitToJsTestApi({ name: 'uni-fteam' })
  if (data) {
    pageData.value = data
  }
  if (err) {
    pageData.value = err
  }
}
</script>

<template>
  <view class="m-4 flex flex-col items-stretch gap-32rpx">
    <button class="w-full" @click="getTest">GET 请求</button>
    <button class="w-full" @click="getTestWithKey">GET 请求[自定义KEY]</button>
    <button class="w-full" @click="postTest">POST 请求</button>
    <button class="w-full" @click="delayRequest">3S后返回数据, 可点击下面取消请求取消</button>
    <button class="w-full" @click="cancelRequest">取消 请求</button>
    <button class="w-full" @click="awaitToJs">awaitToJs</button>

    <view class="mt-40rpx">
      {{ pageData }}
    </view>
  </view>
</template>

<style scoped lang="scss">

</style>
